package com.lkm.app_ui.ui.fj;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.m.camera.CameraModule;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.m.order_img.OnGoodImageTackEvent;
import com.lkm.app_ui.ui.fj.img.FjImgTask;
import com.lkm.app_ui.ui.fj.img.OnFjImageTackEvent;
import com.lkm.app_ui.ui.sale.SaleContract;
import com.lkm.comlib.help.ImageViewLoadHelp;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.comlib.ui.BaseHoldAdapter;
import com.lkm.comlib.ui.IHoldView;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyardserver.event.OnSubtotalEvent;

import java.util.ArrayList;
import java.util.List;



public class FjSaleFragment extends MBaseFragment {

    private static FjImgTask fjImgTask;
    
    FjInfo fjInfo = FjApp.install.getFjInfo();
    FjOrder fjOrder = null;

    private Handler mainHandler;
    @Override
    protected int configLayoutResID() {
        return R.layout.fj_fragment_sale;
    }

    @Override
    protected boolean configIsLockKey() {
        return false;
    }

    @Override
    protected boolean configIsPassLockKey() {
        return true;
    }

    private ItemsView itemsView;
    private TextView tv_item_info;
    private GoodImageView goodImageView;

    @Nullable
    public static FjImgTask getFjImgTask() {
        if (fjImgTask == null) {
            CameraModule cameraModule = AppConst.getModuleManager().peekModule(CameraModule.class);
            if(cameraModule!=null)
                fjImgTask = new FjImgTask(cameraModule);

        }
        return fjImgTask;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainHandler = new Handler();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        tv_item_info = findViewById(R.id.tv_item_info);

        reOnSubtotalEvent();
        itemsView = new ItemsView();
        goodImageView = new GoodImageView();
        binfjInfo();
    }

    

    private void reShow() {

        if (fjOrder == null) {
            
            ((TextView) findViewById(R.id.tv_order_info)).setText("");

            tv_item_info.setText("");
            return;
        }

        int noWeightCount = 0;
        List<FjOrder.FjItem> souceList = new ArrayList<>();
        for (FjOrder.FjItem item : fjOrder.fjItems) {
            if (!StringHelp.isEmpty(item.realWeight)) {
                souceList.add(item);
            } else {
                noWeightCount++;
            }
        }
        itemsView.setSouceList(souceList);


        FjWaitOrder fjWaitOrder = FjApp.install.getFjWaitOrder();

        FjOrder.FjItem fjItem = fjInfo.getCurFjItem();
        if (fjItem == null) {
            tv_item_info.setVisibility(View.GONE);
        } else {
            tv_item_info.setVisibility(View.VISIBLE);
            tv_item_info.setText(Html.fromHtml(
                    "商品：<font color='#CD8500' size='70px'><big>" + fjItem.goodsName + " </big></font>" +
                            "   ；   重量：<font color='red' size='30px'><big>" + fjItem.weight + "</big> </font>" + RunTimeData.getAppWeightUnit() +
                            "   ；   价格：<font color='red' size='30px'><big>" + fjItem.price + "</big></font>元"
//                            "   ；   过秤：<font color='red' size='30px'>" + (fjItem.realWeight == null ? "" : fjItem.realWeight) + RunTimeData.getAppWeightUnit() + "</font>"
            ));
        }
        if (fjOrder == null) {
            ((TextView) findViewById(R.id.tv_order_info)).setVisibility(View.GONE);
        } else {
            ((TextView) findViewById(R.id.tv_order_info)).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.tv_order_info)).setText(Html.fromHtml(
                    "订单号：<font color='red' size='30px'><big>" + fjOrder.fjInfoNo + "</big></font>" +
                            "   ；   未过秤商品： <font color='red' size='70px'><big>" + noWeightCount + "</big></font>件"));
        }
        ((TextView) findViewById(R.id.tv_waitorder)).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.tv_waitorder)).setText(Html.fromHtml(
                "挂起订单数：<font color='red' size='30px'> <big>" + fjWaitOrder.getSize() + "</big></font>单" +
                        "   ；   总订单：<font color='red' size='30px'> <big>" + fjInfo.orderCount + "</big></font>单")
        );

    }


    

    private void binfjInfo() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnFjInfoEvent>() {

            @Override
            public void onReceiver(OnFjInfoEvent data) {
                fjInfo = FjApp.install.getFjInfo();
                fjOrder = fjInfo == null ? null : fjInfo.getCurFjOrder();
                
                if (!isExit())
                    reShow();
            }

            @Override
            public Class<OnFjInfoEvent> getBusEventClass() {
                return OnFjInfoEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    Observer observer;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LinkBus.unregisterReceiver(observer);
        System.out.println("=== onDestroyView FjSaleFragment");
    }


    
    private void reOnSubtotalEvent() {
        LinkBus.registerReceiver(0, observer = new Observer<OnSubtotalEvent>() {
            @Override
            public Class<OnSubtotalEvent> getBusEventClass() {
                return OnSubtotalEvent.class;
            }

            @Override
            public void onReceiver(OnSubtotalEvent data, Runnable nextRun) {
                AppConst.mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        postonReceiver(data);
                        nextRun.run();
                    }
                });
            }

            private void postonReceiver(OnSubtotalEvent data) {
                if (data.isHandleSale()) return;
                
                data.setHandleSale(true);

                if (fjInfo == null) return;
                FjOrder.FjItem curFjItem = fjInfo.getCurFjItem();
                if (curFjItem == null) return;

                OrderEntity.GoodEntity goodEntity = data.getGoodEntitie();
                if (goodEntity.weight < 0) {
                    
                    return;
                }
                if (goodEntity.weight == 0) {
                    AppUIHelp.tryShowTipsSHORT("重量为0,已经判定该商品为缺货");
                }

                if (FjApp.install.fjItemWeight("" + goodEntity.weight)) {
                    FjImgTask fjImgTask = getFjImgTask();
                    if (fjImgTask != null)
                        fjImgTask.requestTackImg(curFjItem);

                }
                else
                    AppUIHelp.tryShowTipsSHORT("当前无过秤对象");

                
                if (fjInfo.getCurFjItem() == null) {

                    mainHandler.postDelayed(onGoodImageTackrun = new Runnable() {
                        @Override
                        public void run() {
                            
                            if (onGoodImageTackrun != null) {
                                onGoodImageTackrun = null;
                                AppUIHelp.tryShowTipsSHORT("过秤成功，分拣完毕，请提交订单");
                                RouterUINavigation.getInstance().showPayFjOrder((BaseFragmentActivity) getActivity());
                            }
                        }
                    }, AppConfig.isOrderImgTack() ? 3500 : 0);
                    if(RunTimeData.steelyardInfo.upDataApiTo==null||!RunTimeData.steelyardInfo.upDataApiTo.isUpImage())
                        onGoodImageTackrun.run();

                }else {
                    AppUIHelp.tryShowTipsSHORT("过秤成功，请继续分拣商品");
                }


            }
        });
    }
    private Runnable onGoodImageTackrun;

    private class ItemsView {
        private ListView listView;
        private ItemsView.MAdapter adapter;
        private List<FjOrder.FjItem> souceList = new ArrayList<>();

        public void setSouceList(List<FjOrder.FjItem> souceList) {
            this.souceList = souceList;
            adapter.notifyDataSetChanged();
        }

        public ItemsView() {
            ((TextView) findViewById(R.id.tv_weight_unit_title)).setText("重量(" + RunTimeData.getAppWeightUnit() + ")");
            listView = findViewById(R.id.vg_list).findViewById(android.R.id.list);
            listView.setAdapter(adapter = new ItemsView.MAdapter());
        }


        private class MAdapter extends BaseHoldAdapter {
            public MAdapter() {
                super(holdCycleHelp());
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();

            }

            @Override
            public IHoldView createHoldView(int position, View convertView, ViewGroup parent) {
                return new ItemsView.MHoldView();
            }

            @Override
            public int getCount() {
                return CollectionHelp.getSize(souceList);
            }

            @Override
            public Object getItem(int position) {
                return souceList.get(position);
            }
        }

        private class MHoldView extends LinearLayout implements IHoldView<FjOrder.FjItem> {

            private TextView tv_name, tv_price_unit, tv_weight, tv_totalPrice, tv_no;

            public MHoldView() {
                super(getActivity());
                ViewHelp.inflate(getActivity(), R.layout.item_sales, this);
                tv_no = (TextView) this.findViewById(R.id.tv_no);
                tv_name = (TextView) this.findViewById(R.id.tv_name);
                tv_price_unit = (TextView) this.findViewById(R.id.tv_price_unit);
                tv_weight = (TextView) this.findViewById(R.id.tv_weight);
                tv_totalPrice = (TextView) this.findViewById(R.id.tv_totalPrice);

            }

            private int position;

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public Object binData(FjOrder.FjItem obj, int position, boolean isonPause) {
                this.position = position;


                setBackgroundColor(position % 2 == 1 ? Color.YELLOW : Color.TRANSPARENT);
                tv_no.setText("" + (position + 1));
                tv_name.setText(obj.goodsName);
                tv_price_unit.setText(SteelardHelp.formatMoney(obj.price));
//                tv_weight.setText(NumberHelp.formatMoney(obj.weight, 3, "--"));
                tv_weight.setText(obj.weight);

                tv_totalPrice.setText(obj.realWeight);

                setTag(obj);
                return null;
            }

        }   

    }


    private class GoodImageView {

        private ImageView img_good;
        private ImageViewLoadHelp payImageViewLoadHelp;


        public GoodImageView() {

            img_good = getActivity().findViewById(R.id.img_good);
            payImageViewLoadHelp = new ImageViewLoadHelp(getActivity(), Math.max(getResources().getDisplayMetrics().heightPixels, getResources().getDisplayMetrics().widthPixels), holdCycleHelp());
            payImageViewLoadHelp.setHasImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
            payImageViewLoadHelp.setLoadingImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
            payImageViewLoadHelp.setNotImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
            reOnGoodImageTackEvent();

        }

        
        private void reOnGoodImageTackEvent() {
            LinkBusCycleWrapper.register(new ObserverAutoNext<OnFjImageTackEvent>() {
                private void postonReceiver(OnFjImageTackEvent data) {

                    if (isExit())return;
                    goodImageView.showTackGoodImage(data.imgPath);

                    if (onGoodImageTackrun != null)
                        onGoodImageTackrun.run();
                }

                @Override
                public void onReceiver(OnFjImageTackEvent data) {
                    if (isExit())return;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            postonReceiver(data);
                        }
                    });
                }

                @Override
                public Class<OnFjImageTackEvent> getBusEventClass() {
                    return OnFjImageTackEvent.class;
                }
            }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
        }
        public void showTackGoodImage(String imgPath) {

            if (isExit()) return;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    payImageViewLoadHelp.setImage(img_good, imgPath);
                    AlphaAnimation animation = new AlphaAnimation(1, 0);
                    animation.setFillAfter(true);
                    animation.setDuration(500);
                    animation.setStartOffset(1000);

                    ((View) img_good.getParent()).startAnimation(animation);
                }
            });


        }


    }


}
